<template>
  <div v-if="visible">
    <JModal
      :title="title"
      :width="width"
      :fullscreen="true"
      :canFullscreen="true"
      wrapClassName="process-common-modal"
      v-model:open="visible"
      cancelText="关闭"
      :okButtonProps="{ style: { display: 'none' } }"
      :cancelButtonProps="{ style: { display: 'none' } }"
    >
      <component :is="bbb" v-bind="routeProps" />
    </JModal>
  </div>
  <div v-if="visibleiframe" v-loading="loadingiframe">
    <JModal
      :title="title"
      :width="width"
      :fullscreen="true"
      :canFullscreen="true"
      v-model:open="visibleiframe"
      cancelText="关闭"
      :okButtonProps="{ style: { display: 'none' } }"
      :cancelButtonProps="{ style: { display: 'none' } }"
    >
      <iframe id="iframebacklog" :src="externalUrl" frameborder="0" style="width: 100%; height: 100%" @load="onIframeLoaded"></iframe>
    </JModal>
  </div>
  <div class="management-page">
    <div class="operation-box">
      <div class="filter-container">
        <a-form layout="inline" :model="filterForm">
          <a-form-item label="">
            <a-select v-model:value="filterForm.selectedroles" style="width: 200px" placeholder="请选择" @change="handleFilterChange">
              <a-select-option value="1">显示委托代办</a-select-option>
              <a-select-option value="2">过滤委托待办</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-input v-model:value="filterForm.subject" placeholder="流程名称，任务主题，申请人" style="width: 250px" @pressEnter="handleSearch" />
          </a-form-item>

          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon><SearchOutlined /></template>
              查询
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset"> 重置 </a-button>
          </a-form-item>
        </a-form>
      </div>
      <a-button :disabled="selectedRowKey?.length === 0" type="primary" @click="agreebacklog"> 同意 </a-button>
      <a-alert style="height: 38px; margin: 8px 0px 0px 0px" type="info" show-icon class="alert">
        <template #message>
          <template v-if="selectedRowKey.length > 0">
            <span>
              <span>已选中 {{ selectedRowKey.length }} 条记录</span>
            </span>
            <a-divider type="vertical" />
          </template>
          <template v-else>
            <span>未选中任何数据</span>
          </template>
        </template>
      </a-alert>
    </div>
    <div class="table-container">
      <div class="vex-table-container">
        <vxe-table
          @checkbox-all="selectAllChangeEvent"
          @checkbox-change="selectChangeEvent"
          ref="tableRef"
          :row-config="{ isHover: true }"
          border
          max-height="100%"
          :loading="loading"
          :data="tableData"
          :column-config="{ resizable: true }"
          :checkbox-config="checkboxConfig"
          header-align="center"
          id="task_instance_id"
          :filter-config="{ remote: true }"
          @filter-change="filterChangeEvent"
          @sort-change="sortChangeEvent"
        >
          <vxe-column type="checkbox" width="70" align="center" />
          <vxe-column type="seq" title="序号" width="70" align="center" />
          <vxe-column
            v-for="item in columns"
            :key="item.key"
            :field="item.dataIndex"
            :title="item.title"
            :show-header-overflow="item.sorter ? false : 'title'"
            :show-overflow="item.sorter ? false : 'title'"
            min-width="150"
            :sortable="!!item.sorter"
            :align="item.key === 'create_time' ? 'center' : 'left'"
            header-align="center"
            :filters="item.filters"
          >
            <template #default="{ row }">
              <a v-if="item.key === 'subject'" class="subject-cell" @click="gotourl(row)"> {{ row[item.dataIndex] }} </a>
              <div v-else-if="item.key === 'applicant'" class="applicant-cell">
                <a-avatar
                  size="small"
                  style="margin-right: 8px; background-color: #1890ff; object-fit: cover"
                  :src="row.initiator.avatar_url ? row.initiator.avatar_url : ''"
                >
                  {{ row.initiator.avatar_url ? '' : row.initiator.employee_name.slice(0, 2) }}
                </a-avatar>
                <div>
                  <div>{{ (row.initiator.department_name || '-') + '-' + (row.initiator.employee_name || '-') }}</div>
                </div>
              </div>
              <span v-else-if="item.key === 'exist_time'"> {{ calculateTimeDiff(row[item.dataIndex]) }} </span>
              <span v-else-if="item.key === 'create_time'"> {{ formatTimestamp(row[item.dataIndex]) }} </span>
              <span v-else>{{ row[item.dataIndex] }}</span>
            </template>
          </vxe-column>
          <template #empty>
            <div class="empty-box">
              <img :src="noDataPng" alt="" />
              <div>暂无数据</div>
            </div>
          </template>
        </vxe-table>
      </div>
      <Pagination
        v-model:current="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :show-total="pagination.showTotal"
        showSizeChanger
        :page-size-options="pagination.pageSizeOptions"
        showQuickJumper
        size="small"
        @change="(current, size) => handleTableChange({ current, pageSize: size })"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted, computed, defineAsyncComponent, onBeforeUnmount } from 'vue';
  import { SearchOutlined } from '@ant-design/icons-vue';
  import { message, Pagination } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import noDataPng from '/@/assets/images/table_nodata.png';
  import { VxeTableInstance, VxeTableEvents, VxeTablePropTypes } from 'vxe-table';

  import { backloglist, backlogagree } from './user.api';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';

  const title = ref('我的待办');
  const loadingiframe = ref(true);
  const width = ref(800);
  const disableSubmit = ref(false);
  const visibleiframe = ref(false);
  const externalUrl = ref('');
  const filters = ref({ filtersall: [] });
  const tableRef = ref<VxeTableInstance<any>>();
  const filtersch = ref('');
  const tableKey = ref(0);
  let time_sort = 'desc'
  const forceReset = () => {
    tableKey.value += 1;
  };
  const onIframeLoaded = () => {
    loadingiframe.value = false;
    toggleIframe(visibleiframe.value);
  };
  window.setvvisible = () => {
    visibleiframe.value = false;
    visible.value = false;
    handleReset();
  };
  window.handleiframe = (data) => {
    visibleiframe.value = false;
    visible.value = false;
    handleReset();
  };
  onBeforeUnmount(() => {
    delete window.setvvisible; // 避免内存泄漏
    delete window.handleiframe;
  });
  const toggleIframe = () => {
    const iframebacklog = document.getElementById('iframebacklog');
  };
  const { createConfirm, createMessage } = useMessage();
  // 表格列定义
  const columns = computed(() => [
    {
      title: '流程标题',
      dataIndex: 'subject',
      key: 'subject',
      ellipsis: true,
      slots: { customRender: 'subject' },
      width: 'auto',
    },
    {
      title: '流程类型',
      dataIndex: 'process_type',
      key: 'process_type',
      filters: filters.value.filtersall,
      filterMode: 'tree',
      filterSearch: false,
      ellipsis: true,
      width: 'auto',
    },
    {
      title: '申请人',
      dataIndex: 'applicant',
      key: 'applicant',
      slots: { customRender: 'applicant' },
      ellipsis: true,
      width: '15%',
      width: 'auto',
    },
    {
      title: '在手时长',
      dataIndex: 'exist_time',
      key: 'exist_time',
      slots: { customRender: 'exist_time' },
      sorter: (a, b) => a.exist_time - b.exist_time,
      ellipsis: true,
      width: 'auto',
    },
    {
      title: '发起时间',
      dataIndex: 'create_time',
      key: 'create_time',
      slots: { customRender: 'create_time' },
      // sorter: (a, b) => a.create_time - b.create_time,
      ellipsis: true,
      width: 'auto',
    },
  ]);

  // 筛选表单数据
  const filterForm = reactive({
    selectedroles: '1',
    subject: '',
  });
  const router = useRouter();
  const bbb = ref();
  const routeProps = ref();
  const visible = ref(false);
  // 表格数据
  const tableData = ref([]);

  const loading = ref(false);
  let selectedRowKey = ref<Key[]>([]);
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100'],
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条`,
    size: 'small',
  });

  // 初始化加载数据
  onMounted(() => {
    fetchData('1');
  });
  const calculateTimeDiff = (timestamp) => {
    const seconds = Math.floor(timestamp / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    return `${days}天${hours % 24}时${minutes % 60}分${seconds % 60}秒`;
  };
  const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  // 获取数据方法
  const fetchData = async (ifone?, query?) => {
    try {
      loading.value = true;

      // 调用listall接口
      const data = {
        page: {
          page_index: pagination.current,
          page_size: pagination.pageSize,
        },
        query: {
          time_sort: query?.time_sort || time_sort,
          status: 'approve',
          merge_task_flag: filterForm.selectedroles === '1' ? false : true,
          subject: filterForm.subject ? filterForm.subject : '',
          type_key_list: filtersch.value,
        },
      };

      const response = await backloglist(data);
      if (response.code === '000000') {
        const currentTime = new Date().getTime();
        // console.log(currentTime, 239);

        tableData.value = response.data.rows;
        tableData.value.forEach((item) => {
          item['exist_time'] = currentTime - item.create_time;
        });
        pagination.total = response.data.page.total;
        const filtersall = response.data.rows
          .filter((item, index, self) => self.findIndex((i) => i.process_type === item.process_type) === index)
          .map((item) => {
            return { text: item.process_type, value: item.process_type_id, label: item.process_type };
          });
        if (ifone === '1') {
          filters.value.filtersall = filtersall;
        }
      } else {
        message.error(response.data.message || '获取数据失败');
      }
    } catch (error) {
      message.error('获取数据出错');
    } finally {
      loading.value = false;
    }
  };

  // 筛选条件变化处理
  const handleFilterChange = () => {
    pagination.current = 1; // 重置到第一页
    // console.log(238, 'handleFilterChange');
    fetchData();
  };

  // 搜索处理
  const handleSearch = () => {
    pagination.current = 1;
    // console.log(245, 'handleSearch');
    fetchData();
  };

  // 重置处理
  const handleReset = () => {
    filterForm.selectedroles = '1';
    filterForm.subject = '';
    pagination.current = 1;
    filters.value.filtersall = [];
    filtersch.value = '';
    selectedRowKey.value = [];
    forceReset();
    fetchData('1');
  };

  // 表格变化处理（分页、排序）
  const handleTableChange = (pag: any, filters?, sorter?) => {
    pagination.current = pag.current;
    pagination.pageSize = pag.pageSize;
    // 这里可以处理排序逻辑
    // console.log(filters, sorter, 260);
    // if (JSON.stringify(filters) !== '{}') {
    //   const filtersstr = filters?.process_type.join(',');
    //   filtersch.value = filtersstr;
    // }
    if (Array.isArray(filters)) {
      filtersch.value = filters[0]?.values.join(',');
    }
    // console.log(filtersch.value, 285);
    fetchData();
  };

  // 处理按钮点击
  const handleProcess = (record) => {
    console.log('处理记录:', record);
    message.info(`处理流程: ${record.name}`);
  };

  // 详情按钮点击
  const agreebacklog = () => {
    createConfirm({
      iconType: 'warning',
      title: '确认操作',
      content: '是否审批选中数据?',
      onOk: async () => {
        try {
          loading.value = true;

          const data = selectedRowKey.value.map((item) => ({ agent_id: item.initiator.employee_id, task_instance_id: item.task_instance_id }));

          const response = await backlogagree(data);
          if (response.code === '000000') {
            // console.log(response);
            createMessage.success('操作成功');
            handleReset();
          } else {
            message.error(response.data.message || '获取数据失败');
          }
        } catch (error) {
          message.error('获取数据出错');
        } finally {
          loading.value = false;
        }
      },
    });
  };
  const gotourl = (record) => {
    // console.log(452, record);
    // if (!record.allow_batch_approval) {
    //   createConfirm({
    //     iconType: 'warning',
    //     title: '提示',
    //     content: '此单无法审批',
    //   });
    // } else {
    //   if (!record.relative_url.includes('/apps/api/v1/private/form/dispatcher') && record.relative_url.startsWith('/')) {
    //     if (record.relative_url.includes('154/')) {
    //       console.log(record.relative_url, 154);
    //     }
    //     title.value = record.subject;
    //     const queryString = record.relative_url.split('?')[1];
    //     const keyValuePairs = queryString.split('&');
    //     const result = {};
    //     keyValuePairs.forEach((pair) => {
    //       const [key, value] = pair.split('=');
    //       result[key] = decodeURIComponent(value); // 处理URL编码字符
    //     });
    //     routeProps.value = result;
    //     const route = router.resolve({ path: record.relative_url, query: result });
    //     console.log(route, 190);
    //     let asynccom = route.matched[1]?.components?.default;
    //     console.log(asynccom, 263);
    //     if (asynccom === undefined) {
    //       createMessage.error('未找到该审批页组件,请注册组件');
    //       return;
    //     }
    //     bbb.value = defineAsyncComponent(asynccom);
    //     visible.value = true;
    //   } else {
    //     // const localUrl = window.location.origin;
    //     // console.log(localUrl, 198);
    //     const url = record.open_url.split('//')[1];
    //     const urlnow = url.substring(url.indexOf('/') + 1);
    //     externalUrl.value = '/' + urlnow;
    //     console.log(externalUrl.value, 303);
    //     visibleiframe.value = true;
    //     loadingiframe.value = true;
    //   }
    // }
    if (!record.relative_url.includes('/apps/api/v1/private/form/dispatcher') && record.relative_url.startsWith('/')) {
      if (record.relative_url.includes('154/')) {
        console.log(record.relative_url, 154);
      }
      title.value = record.subject;
      const queryString = record.relative_url.split('?')[1];
      const keyValuePairs = queryString.split('&');
      const result = {};
      keyValuePairs.forEach((pair) => {
        const [key, value] = pair.split('=');
        result[key] = decodeURIComponent(value); // 处理URL编码字符
      });
      routeProps.value = result;
      const route = router.resolve({ path: record.relative_url, query: result });
      // console.log(route, 190);
      let asynccom = route.matched[1]?.components?.default;
      // console.log(asynccom, 263);
      if (asynccom === undefined) {
        createMessage.error('未找到该审批页组件,请注册组件');
        return;
      }
      bbb.value = defineAsyncComponent(asynccom);
      visible.value = true;
    } else {
      // const localUrl = window.location.origin;
      // console.log(localUrl, 198);
      const url = record.open_url.split('//')[1];
      const urlnow = url.substring(url.indexOf('/') + 1);
      externalUrl.value = '/' + urlnow;
      // console.log(externalUrl.value, 303);
      visibleiframe.value = true;
      loadingiframe.value = true;
    }
  };
  //
  const filterChangeEvent: VxeTableEvents.FilterChange<any> = ({ filterList }) => {
    handleTableChange({ ...pagination, current: 1 }, filterList);
  };
  /**列表选中相关内容 */
  type Key = string | number;
  // const selectedRowKeys = ref<Key[]>([]);
  const selectAllChangeEvent: VxeTableEvents.CheckboxAll<any> = () => {
    const $table = tableRef.value;
    if ($table) {
      // $table.toggleAllCheckboxRow()
      const records = $table.getCheckboxRecords();
      // console.log('records-----', records);
      // selectedRowKey.value = records.map((item) => item.id);
      selectedRowKey.value = records;
    }
  };

  const selectChangeEvent: VxeTableEvents.CheckboxChange<any> = () => {
    const $table = tableRef.value;
    if ($table) {
      // $table.toggleCheckboxRow(row)
      const records = $table.getCheckboxRecords();
      // console.log('records-----', records);
      // selectedRowKeys.value = records.map((item) => item.id);
      selectedRowKey.value = records;
    }
  };

  const checkboxConfig = reactive<VxeTablePropTypes.CheckboxConfig<any>>({
    highlight: true,
    checkMethod: ({ row }) => {
      return row.allow_batch_approval; // 根据a字段禁用勾选
    },
  });

  const sortChangeEvent: VxeTableEvents.SortChange<any> = ({ sortList }) => {
    // console.log(sortList);
    // console.info(sortList.map((item) => `${item.field},${item.order}`).join('; '))
    for (let index = 0; index < sortList.length; index++) {
      const element = sortList[index];
      if (element.field === 'exist_time') {
        time_sort = element.order || ''
      }
    }
    fetchData(undefined, {time_sort});
  }

</script>

<style lang="less" scoped>
  .subject-cell:hover {
    text-decoration: underline;
  }
  .management-page {
    background: #fff;
    height: 100%;
    padding: 16px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .operation-box {
      box-sizing: border-box;
      padding-bottom: 12px;
    }
  }

  .filter-container {
    padding-bottom: 8px;
    border-radius: 4px;
  }

  .table-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow: hidden;
    .vex-table-container {
      flex: 1;
      overflow: hidden;
    }
  }
  .applicant-cell {
    display: flex;
    align-items: center;
  }

  :deep(.ant-btn-link) {
    padding: 0 4px;
  }
  :deep(.ant-pagination) {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin: 0 !important;
    padding: 16px 20px 0;
    box-sizing: border-box;
    box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
  }
  // vxe 样式
  :deep .vxe-table--render-default .vxe-body--row.row--checked > .vxe-body--column {
    background: #c3d9d1;
  }
  :deep .vxe-table-icon-checkbox-checked-fill,
  .vxe-table-icon-checkbox-indeterminate-fill {
    color: #009a7a !important;
  }
  :deep .vxe-table-icon-checkbox-indeterminate-fill {
    color: #009a7a !important;
  }
  // :deep .row--checked .vxe-checkbox--icon {
  //   color: #009a7a !important;
  // }
</style>
